package com.itcc.service.impl;

import com.itcc.dao.UserDao;
import com.itcc.dao.impl.UserDaoImpl;
import com.itcc.entity.User;
import com.itcc.service.UserService;
import com.itcc.utils.Constants;
import com.itcc.utils.MD5Utils;

import java.sql.SQLException;
import java.util.List;

public class UserServiceImpl  implements UserService {

    @Override
    public boolean checkedUser(String username) throws SQLException {

        //创建Dao访问对象
        UserDao userDao=new UserDaoImpl();
        User user=userDao.selectUserByUname(username);
        if(user!=null){
            return true;
        }
        return false;
    }

    @Override
    public int registerUser(User user) throws SQLException {
    UserDao userDao=new UserDaoImpl();
    int row = userDao.insertUser(user);

    //发送邮件激活客户
//        EmailUtils.sendEmail(user);
        return row;
    }

    @Override
    public int activeUser(String code) throws SQLException {
        //根据激活码查找用户
        UserDao userDao=new UserDaoImpl();

        User user=userDao.selectUserbyCode(code);
        if(user==null){
        return Constants.ACTIVE_FAIL;
    }

        if(user.getUstatus().equals(Constants.USER_ACTIVE)){
            return Constants.ACTIVE_ALREADY;
        }

        int i=userDao.updateStatusByUid(user.getUid());
        if(i>0) return Constants.ACTIVE_SUCCESS;
        return Constants.ACTIVE_FAIL;
    }

    @Override
    public User login(String username, String password) throws SQLException {
        String md5password= MD5Utils.md5(password);

        UserDao userDao=new UserDaoImpl();
        User user = userDao.selectUserByUname(username);
        if (user != null && user.getUpassword().equals(md5password)) {
            return user;
        }

        return null;
    }

    @Override
    public List<User> findAllUsers() throws SQLException {

        UserDao userDao=new UserDaoImpl();
        List<User> userList =userDao.findAllUser();
        return userList;
    }


}
